const startTime = new Date().getTime();
// import { INestApplication } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common';
// import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { Logger } from 'nestjs-pino';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './common/filters/all-exception.filter';
import { BadRequestFilter } from './common/filters/badrequest-execption.filter';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TypeormFilter } from './common/filters/typeorm.filter';
import { connectLogger } from './common/logs4js/log4js.config';
// import { initSession } from './common/middleware/session.middleware';
import { setupSwagger } from './shared/swagger';
import { essionConfig } from './common/session/session.config';
import { ConfigService } from '@nestjs/config';
import { RedisCommonService } from './common/redis/redis.service';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { ConfigEnum } from './common/enum/config.enum';

console.info('启动时间：', new Date().getTime() - startTime);

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    // logger: new Log4jsLogger(), // 代替nestjs内置的logger
  });

  // 配置文件
  const configService = app.get(ConfigService);

  // 文件上传路径
  app.useStaticAssets(
    join(
      __dirname,
      '..',
      configService.get<string>(ConfigEnum['FILE_UPLOADS_DIR']) || 'uploads',
    ),
  );
  // 系统静态文件（需要手动复制到dist下）
  app.useStaticAssets(join(__dirname, '..', 'public'), {
    prefix: '/static/', // 访问前缀
    index: false, // 禁用目录索引
    extensions: ['jpg', 'png', 'gif', 'xlsx'], // 限制文件类型
  });

  // 公共前缀
  app.setGlobalPrefix('/api/v1');

  // session 配置
  const redisCommonService = app.get(RedisCommonService);
  app.use(essionConfig(configService, redisCommonService));

  // 注册 Swagger 的配置顺序
  setupSwagger(app);

  // 全局过滤器(相同类型后面覆盖前面，智慧执行一个)
  app.useLogger(app.get(Logger));
  app.useGlobalFilters(new AllExceptionsFilter(app.get(Logger)));
  app.useGlobalFilters(new HttpExceptionFilter(app.get(Logger)));
  app.useGlobalFilters(new TypeormFilter(app.get(Logger)));
  app.useGlobalFilters(new BadRequestFilter(app.get(Logger)));

  // 应用 log4js HTTP 日志中间件
  app.use(connectLogger);

  // 全局管道
  app.useGlobalPipes(
    new ValidationPipe({
      // 去除类上不存在或没有任何装饰器的属性（express 需要封装函数pick的作用）
      // 控制器中拿到的数据就是干净的数据【提高了输入数据的安全】
      whitelist: true,
    }),
  );

  await app.listen(process.env.PORT ?? 3000);
  console.info('监听时间：', +new Date().getTime() - startTime);
}
void bootstrap();
